package com.biz.primus.service.push.service;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import com.biz.primus.base.vo.push.Notification;
import com.biz.primus.service.push.service.interfaces.IPusher;
import com.biz.primus.service.push.util.PushUtil;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author david-liu
 */
@Component
@Slf4j
public class JPusher implements IPusher {
    @Autowired
    private JPushClient jPushClient;

    @Value("${isProduction}")
    private Boolean isProduction;

    @PostConstruct
    public void setup() {
        log.info("Create bean {} with isProduction:{} success.", getClass(), isProduction);
    }

    @Override
    public void push(Notification notification) {

        try {
            PushResult result = jPushClient.sendPush(PushUtil.buildJPushPayload(notification, isProduction));
            if (result.isResultOK()) {
                log.info("成功发送推送消息[{}]", result.getOriginalContent());
            } else {
                log.warn("发送推送消息[{}]失败, 回复编号[{}]", result.getOriginalContent(), result.getResponseCode());
            }
        } catch (APIConnectionException e) {
            log.warn("连接极光推送API服务中心失败");
        } catch (APIRequestException e) {
            log.warn("请求激光推送API服务中心失败");
        }
    }
}
